package com.future.mayi.qsale.activity;

import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.HttpRequest;
import com.future.baselib.utils.ToastUtils;
import com.google.gson.reflect.TypeToken;
import com.imnjh.imagepicker.activity.PhotoPickerActivity;
import com.future.mayi.R;
import com.future.mayi.activity.BaseTitleActivity;
import com.future.mayi.app.App;
import com.future.mayi.model.interfaces.OnItemClickListener;
import com.future.mayi.qsale.dialog.SalePhotoSampleDialog;
import com.future.mayi.qsale.model.QsaleCateModel;
import com.future.mayi.qsale.model.QsaleGoodsListModel;
import com.future.mayi.qsale.model.UploadMutilFileResponse;
import com.future.mayi.qsale.response.CateListResponse;
import com.future.mayi.qsale.utils.SelectImgUtils;
import com.future.mayi.qsale.view.SelectImgView;
import com.future.mayi.utils.CompressImgUtils;
import com.future.mayi.utils.HCUtils;
import com.future.mayi.utils.Navigator;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 回收
 * Created by Administrator on 2018/6/19.
 */

public class ConsignRecycleActivity extends BaseTitleActivity {


    private SelectImgUtils selectImgUtils;

    @BindView(R.id.select_image_view)
    SelectImgView selectImageView;
    @BindView(R.id.tv_hint)
    TextView tvHint;
    @BindView(R.id.read_photo_sample)
    TextView readPhotoSample;
    @BindView(R.id.iv_brand_arrow)
    ImageView ivBrandArrow;
    @BindView(R.id.tv_brand)
    TextView tvBrand;
    @BindView(R.id.rl_brand)
    RelativeLayout rlBrand;
    @BindView(R.id.iv_style_arrow)
    ImageView ivStyleArrow;
    @BindView(R.id.tv_style)
    TextView tvStyle;
    @BindView(R.id.rl_style)
    RelativeLayout rlStyle;
    @BindView(R.id.tv_hint_price)
    TextView tvHintPrice;
    @BindView(R.id.edt_price)
    EditText edtPrice;
    @BindView(R.id.rl_price)
    RelativeLayout rlPrice;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.edt_size)
    EditText edtSize;
    @BindView(R.id.rl_size)
    RelativeLayout rlSize;
    @BindView(R.id.rl_desc)
    RelativeLayout rlDesc;
    @BindView(R.id.edt_desc)
    EditText edtDesc;
    @BindView(R.id.tv_text_num)
    TextView tvTextNum;
    @BindView(R.id.btn_order_to_sale)
    TextView btnOrderToSale;

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_consign_recycle);

    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initDates() {

    }

    @Override
    protected void initListener() {
        selectImageView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void OnItem(View view, int position) {
                SelectImgUtils selectImgUtils = new SelectImgUtils();
                if (selectImgUtils == null) {
                    selectImgUtils = new SelectImgUtils();
                }
                selectImgUtils.selectImg(ConsignRecycleActivity.this, selectImageView.getMaxSelectNum());
            }

            @Override
            public void OnLongItem(View view, int position) {

            }
        });
        edtDesc.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tvTextNum.setText(edtDesc.getText().toString().length() + "/200");
            }
        });

    }

    @Override
    protected void initTopBar() {
        initBack();
        getTitleText().setText("商品信息");
        getRightText().setText("回收流程");
        getRightText().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigator.navigatorFlowIntroActivity(ConsignRecycleActivity.this, true);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == SelectImgUtils.REQUEST_CODE_IMAGE) {
            final ArrayList<String> pathList = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT_SELECTION);
            if (pathList != null && pathList.size() > 0 && (!TextUtils.isEmpty(pathList.get(0)))) {
                showLoadingDialog();
                CompressImgUtils compressImgUtils = new CompressImgUtils();
                compressImgUtils.compressImg(pathList, new CompressImgUtils.OnCompressImgListener() {
                    @Override
                    public void onSucceed(List<String> pathList) {
                        dissmissLoadingDialog();
                        selectImageView.addImg(pathList);
                    }

                    @Override
                    public void onFailed(Exception e) {
                        dissmissLoadingDialog();
                    }
                });
            }
        }
    }


    @OnClick({R.id.read_photo_sample, R.id.rl_brand, R.id.rl_style, R.id.btn_order_to_sale, R.id.tv_recycler_protocol})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.read_photo_sample:
                SalePhotoSampleDialog salePhotoSampleDialog = new SalePhotoSampleDialog(mContext);
                salePhotoSampleDialog.show();
                break;
            case R.id.rl_brand:
                getRecycleBrand();
                break;
            case R.id.rl_style:
                getRecycleStyle();
                break;
            case R.id.btn_order_to_sale:
                if (verifyInput()) {
                    uploadImage();
                }
                break;
            case R.id.tv_recycler_protocol:
                Navigator.navigatorProtocolActivity(ConsignRecycleActivity.this, true);
                break;
            default:
                break;
        }
    }

    private void getRecycleBrand() {
        showLoadingDialog();
        new HttpRequest<CateListResponse>()
                .with(this)
                .setApiCode(ApiCst.getBrandOrStyle)
                .addParam("type", 30)
                .setListener(new HttpRequest.OnNetworkListener<CateListResponse>() {
                    @Override
                    public void onSuccess(CateListResponse response) {
                        dissmissLoadingDialog();
                        showSelectBrandPickerView(response.getQSaleCateList());
                    }

                    @Override
                    public void onFail(String message, CateListResponse response) {
                        dissmissLoadingDialog();
                        HCUtils.loadFail(ConsignRecycleActivity.this, message);
                    }
                }).start(new CateListResponse());
    }

    private void showSelectBrandPickerView(final List<QsaleCateModel> qsaleCateModels) {
        if (qsaleCateModels == null || qsaleCateModels.size() == 0) return;
        final List<String> brandNames = new ArrayList<>(qsaleCateModels.size());
        for (int i = 0; i < qsaleCateModels.size(); i++) {
            brandNames.add(qsaleCateModels.get(i).getCate_name());
        }
        OptionsPickerView optionsPickerView = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tvBrand.setText(brandNames.get(options1));
                tvBrand.setTag(R.id.cate_id, qsaleCateModels.get(options1).getCate_id());
                tvStyle.setText("");
                tvStyle.setTag(R.id.cate_id, null);
            }
        }).build();
        optionsPickerView.setPicker(brandNames);
        optionsPickerView.show();
    }

    private void getRecycleStyle() {
        if (tvBrand.getTag(R.id.cate_id) == null) {
            ToastUtils.shortToast(this, "请先选择品牌");
            return;
        }
        int cateId = (int) tvBrand.getTag(R.id.cate_id);
        showLoadingDialog();
        new HttpRequest<CateListResponse>()
                .with(this)
                .setApiCode(ApiCst.getBrandOrStyle)
                .addParam("pid", cateId)
                .addParam("type", 30)
                .setListener(new HttpRequest.OnNetworkListener<CateListResponse>() {
                    @Override
                    public void onSuccess(CateListResponse response) {
                        dissmissLoadingDialog();
                        showSelectStylePickerView(response.getQSaleCateList());

                    }

                    @Override
                    public void onFail(String message, CateListResponse response) {
                        dissmissLoadingDialog();
                        HCUtils.loadFail(ConsignRecycleActivity.this, message);
                    }
                }).start(new CateListResponse());

    }

    private void showSelectStylePickerView(final List<QsaleCateModel> qsaleCateModels) {
        if (qsaleCateModels == null || qsaleCateModels.size() == 0) return;
        final List<String> styleNames = new ArrayList<>(qsaleCateModels.size());
        for (int i = 0; i < qsaleCateModels.size(); i++) {
            styleNames.add(qsaleCateModels.get(i).getCate_name());
        }
        OptionsPickerView optionsPickerView = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tvStyle.setText(styleNames.get(options1));
                tvStyle.setTag(R.id.cate_id, qsaleCateModels.get(options1).getCate_id());
            }
        }).build();
        optionsPickerView.setPicker(styleNames);
        optionsPickerView.show();
    }

    private boolean verifyInput() {
        if (selectImageView.getImg() == null || selectImageView.getImg().size() == 0) {
            toast("请选择图片");
            return false;
        }
        if (tvBrand.getTag(R.id.cate_id) == null) {
            toast("请选择品牌");
            return false;
        }
        if (tvStyle.getTag(R.id.cate_id) == null) {
            toast("请选择款式");
            return false;
        }
        if (TextUtils.isEmpty(edtPrice.getText().toString())) {
            toast("请输入期望价格");
            return false;
        }
        return true;
    }

    private void uploadImage() {
        showLoadingDialog();
        new HttpRequest<UploadMutilFileResponse>()
                .with(this)
                .setApiCode(ApiCst.mutiUploadPic)
                .setMutiFilePath(selectImageView.getImg())
                .setListener(new HttpRequest.OnNetworkListener<UploadMutilFileResponse>() {
                    @Override
                    public void onSuccess(UploadMutilFileResponse response) {
                        sendConsignRequest(response.getResponseString());
                    }

                    @Override
                    public void onFail(String message, UploadMutilFileResponse response) {
                        dissmissLoadingDialog();
                    }
                })
                .uploadMutiImage(new UploadMutilFileResponse());
    }

    private void sendConsignRequest(String imageUrl) {

        QsaleGoodsListModel qsaleGoodsListModel = new QsaleGoodsListModel();
        qsaleGoodsListModel.setBrand_name(tvBrand.getText().toString());
        qsaleGoodsListModel.setStyle_name(tvStyle.getText().toString());
        qsaleGoodsListModel.setStyle_id((Integer) tvStyle.getTag(R.id.cate_id));
        qsaleGoodsListModel.setImg_list(imageUrl);
        qsaleGoodsListModel.setSize(edtSize.getText().toString());
        qsaleGoodsListModel.setDescribe(edtDesc.getText().toString());
        qsaleGoodsListModel.setExpect_price(Float.parseFloat(edtPrice.getText().toString()));

        ArrayList<QsaleGoodsListModel> qsaleGoodsListModels = new ArrayList<>();
        qsaleGoodsListModels.add(qsaleGoodsListModel);

        new HttpRequest<DefaultResponse>()
                .with(this)
                .setApiCode(ApiCst.addConsignorder)
                .addParam("token", App.getToken(this))
                .addParam("goods_list", App.getGson().toJson(qsaleGoodsListModels, new TypeToken<List<QsaleGoodsListModel>>() {
                }.getType()))
                .addParam("order_type", 2)
                .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                    @Override
                    public void onSuccess(DefaultResponse response) {
                        String orderId = "";
                        try {
                            JSONObject object = new JSONObject(response.content);
                            orderId = object.optString("order_id");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        dissmissLoadingDialog();
                        toast(response.message);
                        Navigator.navigatorToSucceedConsignActivity(ConsignRecycleActivity.this, orderId, 2);
                        ConsignRecycleActivity.this.finish();
                    }

                    @Override
                    public void onFail(String message, DefaultResponse response) {
                        dissmissLoadingDialog();
                        toast(message);
                    }
                })
                .start(new DefaultResponse());
    }


}
